use sqlx::PgPool;
use crate::models;
use models::metainfo::SongMetaInfo;

#[derive(Clone)]
pub struct UserFavoritesDao {
    pub pool: PgPool,
}

impl UserFavoritesDao {
    pub async fn add_favorite_song(&self, user_id: i64, song_id: i64) -> Result<(), sqlx::Error> {
        sqlx::query(
            r#"
            INSERT INTO user_favorites (user_id, song_id)
            VALUES ($1, $2)
            "#
        )
        .bind(user_id)
        .bind(song_id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    pub async fn remove_favorite_song(&self, user_id: i64, song_id: i64) -> Result<(), sqlx::Error> {
        sqlx::query(
            r#"
            DELETE FROM user_favorites
            WHERE user_id = $1 AND song_id = $2
            "#
        )
        .bind(user_id)
        .bind(song_id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    pub async fn get_favorite_songs(&self, user_id: i64) -> Result<Vec<SongMetaInfo>, sqlx::Error> {
        let songs = sqlx::query_as::<_, SongMetaInfo>(
            r#"SELECT songs.* FROM user_favorites INNER JOIN songs ON user_favorites.song_id = songs.song_id WHERE user_id = $1"#
        )
        .bind(user_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(songs)
    }
}